package com.yumei.trader.gym.page;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.SkuDetails;
import com.yumei.trader.gym.R;
import com.yumei.trader.gym.client.BasePage;
import com.yumei.trader.gym.client.TGApplication;
import com.yumei.trader.gym.dbase.sqlite.SqliteActObject;
import com.yumei.trader.gym.google.GoogleConst;
import com.yumei.trader.gym.google.GoogleHelper;
import com.yumei.trader.gym.ktx.MCallBack;
import com.yumei.trader.gym.object.ActObj;
import com.yumei.trader.gym.util.StringUtils;
import com.yumei.trader.gym.dbase.DBaseConst;

public class PageAppHome extends BasePage {

    private TextView userAssets, userStarNumber;
    private RatingBar ratingBar;
    private ImageView shopImg;
    private ImageView voiceImg, musicImg;
    private ImageView tvStart;
    private String isOpenVoice, isOpenMusic;

    private SqliteActObject sqLiteAccObj;

    private ActObj accountEl;
    private TGApplication mApp;

    private String haveReward = "";

    private GoogleHelper googleObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApp = (TGApplication) this.getApplication();

        haveReward = getIntent().getStringExtra("haveReward");
        googleObject = GoogleHelper.initInstance(this, GoogleConst.base64EncodedPublicKey);

        setContentView(R.layout.page_app_home);
        sqLiteAccObj = SqliteActObject.getInstance(this);

        registerView();
    }


    @Override
    protected void onResume() {
        super.onResume();

        transparentBar();
        initData();
    }

    @Override
    public void onBackPressed() {
        //startActivityForResult(PagePpExitApp.class, 0x106);
    }

    @SuppressLint("SetTextI18n")
    private void registerView() {

        ratingBar = this.findViewById(R.id.game_home_game_star_rating);
        shopImg = this.findViewById(R.id.home_shop_img);
        // shopImg.startAnimation(wobbleAnimation(3));
        userStarNumber = this.findViewById(R.id.game_home_game_star_number);

        isOpenVoice = mApp.getDBMrg().getValue(DBaseConst.Is_Open_Voice, "true");
        isOpenMusic = mApp.getDBMrg().getValue(DBaseConst.Is_Open_Music, "true");

        userAssets = this.findViewById(R.id.home_user_assets);

        voiceImg = this.findViewById(R.id.home_voice_img);
        if (isOpenVoice.equals("true")) {
            voiceImg.setImageResource(R.mipmap.ic_voice_open);
        } else {
            voiceImg.setImageResource(R.mipmap.ic_voice_close);
        }
        musicImg = this.findViewById(R.id.home_music_img);
        if (isOpenMusic.equals("true")) {
            musicImg.setImageResource(R.mipmap.ic_music_open);
        } else {
            musicImg.setImageResource(R.mipmap.ic_music_close);
        }

        tvStart = this.findViewById(R.id.home_start_game);
        tvStart.setOnClickListener(clickListener);

        this.findViewById(R.id.guide_about_us_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.home_voice_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.home_music_layout).setOnClickListener(clickListener);
        shopImg.setOnClickListener(clickListener);


        checkSubscribe();
        checkSubscribePrice();
    }

    private void checkSubscribe() {

        boolean result = googleObject.executeQueryPurchases(GoogleConst.productId);
        if (result) {
            TGApplication.vipUser = true;
            shopImg.setVisibility(View.GONE);
        } else {
            TGApplication.vipUser = false;
            shopImg.setVisibility(View.VISIBLE);
        }
    }

    private void checkSubscribePrice() {

        googleObject.executeQuerySkuDetails(GoogleConst.productId, (billingResult, skuDetailsList) -> {

            int code = billingResult.getResponseCode();

            if (BillingClient.BillingResponseCode.OK == code) {

                assert skuDetailsList != null;
                for (SkuDetails sku : skuDetailsList) {

                    if (sku.getSku().equalsIgnoreCase(GoogleConst.productId)) {

                        GoogleConst.SubPrice = sku.getPrice();
                    }
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void initData() {

        ActObj resultAccount = sqLiteAccObj.getAccount(mApp.getUserId());
        if (!StringUtils.isNull(resultAccount.userId)) {
            accountEl = resultAccount;
        } else {
            sqLiteAccObj.insert(new ActObj(mApp.getUserId()));
            accountEl = sqLiteAccObj.getAccount(mApp.getUserId());
        }

        if (!StringUtils.isNull(haveReward)) {
            int addNumber;
            int diffNumber = (int) (5 - accountEl.useTimes);
            if (diffNumber >= 0) {
                if (haveReward.equals("yes")) {
                    accountEl.useTimes = 5;
                    addNumber = diffNumber;
                } else {
                    if (diffNumber <= 2) {
                        accountEl.useTimes = 5;
                        addNumber = diffNumber;
                    } else {
                        accountEl.useTimes = accountEl.useTimes + 2;
                        addNumber = 2;
                    }
                }
                sqLiteAccObj.updateTimes(mApp.getUserId(), addNumber);
            }
        }

        userAssets.setText("$ " + StringUtils.moneyFormat(accountEl.account, 2));

        ratingBar.setRating(TGApplication.vipUser ? 2 : accountEl.useTimes);

        ratingBar.setClickable(false);

        int starNum = (int) accountEl.useTimes;
        if (TGApplication.vipUser) {
            tvStart.setImageResource(R.mipmap.ic_home_pay);
            userStarNumber.setText("x5");
        } else {
            userStarNumber.setText("x" + (int) accountEl.useTimes);
            if (starNum <= 0) { //无
                tvStart.setImageResource(R.mipmap.ic_home_pay_);
            } else {
                tvStart.setImageResource(R.mipmap.ic_home_pay);
            }
        }

        double diffMoney = accountEl.account - 100000d;
        if (diffMoney > 0) {
            userAssets.setTextColor(ContextCompat.getColor(this, R.color.color_stock_down));
        } else if (diffMoney < 0) {
            userAssets.setTextColor(ContextCompat.getColor(this, R.color.color_stock_up));
        } else {
            userAssets.setTextColor(ContextCompat.getColor(this, R.color.color_font_main));
        }

        if (TGApplication.vipUser) {
            shopImg.setVisibility(View.GONE);
        } else {
            shopImg.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 主体UI点击时间控制中枢
     */
    private final View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (v.getId() == R.id.home_start_game) {
                haveReward = "";
                if (TGApplication.vipUser) {
                    startActivity(PageGamePlay.class);
                } else {
                    if (accountEl.useTimes >= 1.0f) {
                        startActivity(PageGamePlay.class);
                    } else {
                        noStarAction();
                    }
                }
            } else if (v.getId() == R.id.guide_about_us_layout) {
                startActivity(PagePpAgreement.class);
            } else if (v.getId() == R.id.home_voice_layout) {

                if (isOpenVoice.equals("true")) {
                    isOpenVoice = "false";
                    voiceImg.setImageResource(R.mipmap.ic_voice_close);
                } else {
                    isOpenVoice = "true";
                    voiceImg.setImageResource(R.mipmap.ic_voice_open);
                }
                mApp.getDBMrg().addParam(DBaseConst.Is_Open_Voice, isOpenVoice);
                mApp.getDBMrg().save();

            } else if (v.getId() == R.id.home_music_layout) {
                if (isOpenMusic.equals("true")) {
                    isOpenMusic = "false";
                    musicImg.setImageResource(R.mipmap.ic_music_close);
                } else {
                    isOpenMusic = "true";
                    musicImg.setImageResource(R.mipmap.ic_music_open);
                }
                mApp.getDBMrg().addParam(DBaseConst.Is_Open_Music, isOpenMusic);
                mApp.getDBMrg().save();
            } else if (v.getId() == R.id.home_shop_img) {
                startActivity(PageAppPay.class);
            }

        }
    };

    private void noStarAction() {
        // startActivity(PagePpSubscribe.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x106 && resultCode == 0x200) {
            onBackAction();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //拦截返回键
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //判断触摸UP事件才会进行返回事件处理
            if (event.getAction() == KeyEvent.ACTION_UP) {
                onBackPressed();
            }
            //只要是返回事件，直接返回true，表示消费掉
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


}
